package com.csproj.dispatch.service;

import com.csproj.dispatch.domain.ProductDetailInfo;
import com.csproj.dispatch.domain.ProductInfo;
import com.csproj.dispatch.repository.ProductDetailInfoRepository;
import com.csproj.dispatch.repository.ProductInfoRepository;
import com.csproj.dispatch.service.dto.ProductDetailInfoDTO;
import com.csproj.dispatch.service.dto.ProductInfoDTO;
import com.csproj.dispatch.service.mapper.ProductDetailInfoMapper;
import com.csproj.dispatch.service.mapper.ProductInfoMapper;
import com.csproj.siiat.base.common.dto.BaseDTO;
import com.csproj.siiat.security.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Service Implementation for managing ProductInfo.
 */
@Service
@Transactional
public class ProductInfoService {

    private final Logger log = LoggerFactory.getLogger(ProductInfoService.class);

    private final ProductInfoRepository productInfoRepository;

    private final ProductDetailInfoRepository productDetailInfoRepository;

    private final ProductInfoMapper productInfoMapper;

    private final ProductDetailInfoMapper productDetailInfoMapper;

    public ProductInfoService(ProductInfoRepository productInfoRepository, ProductInfoMapper productInfoMapper,
                              ProductDetailInfoRepository productDetailInfoRepository, ProductDetailInfoMapper productDetailInfoMapper) {
        this.productInfoRepository = productInfoRepository;
        this.productInfoMapper = productInfoMapper;
        this.productDetailInfoRepository = productDetailInfoRepository;
        this.productDetailInfoMapper = productDetailInfoMapper;
    }

    /**
     * Save a productInfo.
     *
     * @param productInfoDTO the entity to save
     * @return the persisted entity
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseDTO save(ProductInfoDTO productInfoDTO) {
        log.debug("Request to save ProductInfo : {}", productInfoDTO);
        ProductInfo productInfo = productInfoMapper.toEntity(productInfoDTO);
        Set<ProductDetailInfoDTO> productDetailInfoDTOS = productInfoDTO.getProductDetailInfoDTOS();
        if(productInfo.getContainerId()!=null && !"".equals(productInfo.getContainerId())){
            //保存货物基本信息
            // 设置创建时间、创建人
            productInfo.setCreationTime(ZonedDateTime.now());
            productInfo.setCreatorUserId(SecurityUtils.getCurrentUserId());
            productInfo.setLastModificationTime(ZonedDateTime.now());
            productInfo.setLastModifierUserId(SecurityUtils.getCurrentUserId());
            productInfo = productInfoRepository.save(productInfo);
            productInfoDTO = productInfoMapper.toDto(productInfo);

            //保存商品信息
            if(productDetailInfoDTOS!=null && !productDetailInfoDTOS.isEmpty()){
                List<ProductDetailInfo> productDetailInfoList = productDetailInfoMapper.toEntity(new ArrayList<>(productDetailInfoDTOS));
                System.out.println(productDetailInfoList.size());
                //设置外键货物id
                for(ProductDetailInfo productDetailInfo : productDetailInfoList){
                    productDetailInfo.setInfoId(productInfo.getId());
                    productDetailInfo.setCreationTime(ZonedDateTime.now());
                    productDetailInfo.setCreatorUserId(SecurityUtils.getCurrentUserId());
                    productDetailInfo.setLastModificationTime(ZonedDateTime.now());
                    productDetailInfo.setLastModifierUserId(SecurityUtils.getCurrentUserId());
                }
                productDetailInfoList = productDetailInfoRepository.save(productDetailInfoList);
                productInfoDTO.setProductDetailInfoDTOS(new HashSet<>(productDetailInfoMapper.toDto(productDetailInfoList)));
            }
            return BaseDTO.createBaseDTO(productInfoDTO);
        }else{
            return new BaseDTO(BaseDTO.CODE_PARAM, "container_code_not_null", null);
        }

    }

    /**
     * Get all the productInfos.
     *
     * @return the list of entities
     */
    @Transactional(readOnly = true)
    public List<ProductInfoDTO> findAll() {
        log.debug("Request to get all ProductInfos");
        return productInfoRepository.findAll().stream()
            .map(productInfoMapper::toDto)
            .collect(Collectors.toCollection(LinkedList::new));
    }

    /**
     * 通过集装箱id获取货物信息以及商品详细信息
     * @param containerId 集装箱id
     * @return
     */
    public BaseDTO searchProductInfoByContainerIdId(String containerId){
        if(containerId==null || containerId.equals("")){
            return new BaseDTO(BaseDTO.CODE_PARAM, "container_code_not_null", null);
        }
        ProductInfo productInfo = productInfoRepository.findFirstByContainerIdAndDeletionTimeIsNull(containerId);
        ProductInfoDTO productInfoDTO = productInfoMapper.toDto(productInfo);
        if(productInfo != null){
            List details = productDetailInfoRepository.findAllByInfoIdAndDeletionTimeIsNull(productInfo.getId());
            if(details!=null){
                List<ProductDetailInfoDTO> productDetailInfoDTOS = productDetailInfoMapper.toDto(details);
                productInfoDTO.setProductDetailInfoDTOS(new HashSet<>(productDetailInfoDTOS));
            }
        }
        return BaseDTO.createBaseDTO(productInfoDTO);
    }

    /**
     * 修改货物信息
     * @param id 货物信息主键
     * @param productInfoDTO 货物信息
     * @return
     */
    public BaseDTO updateProductInfo(String id, ProductInfoDTO productInfoDTO){
        if(id==null || "".equals(id)){
            return new BaseDTO(BaseDTO.CODE_PARAM, "product_info_key_not_null", null);
        }
        Set<ProductDetailInfoDTO> productDetailInfoDTOS = productInfoDTO.getProductDetailInfoDTOS();
        //更新货物信息
        log.debug("开始更新货物信息");
        ProductInfo productInfo = productInfoMapper.toEntity(productInfoDTO);
        productInfo.setId(id);
        productInfo.setLastModificationTime(ZonedDateTime.now());
        productInfo.setLastModifierUserId(SecurityUtils.getCurrentUserId());
        productInfo = productInfoRepository.save(productInfo);
        productInfoDTO = productInfoMapper.toDto(productInfo);

        if(productDetailInfoDTOS!=null && !productDetailInfoDTOS.isEmpty()){
            log.debug("开始更新商品明细信息");
            //删除原有的商品详细信息
            productDetailInfoRepository.deleteAllByInfoId(productInfo.getId());
            //插入最新的商品详细信息
            List<ProductDetailInfo> productDetailInfos = productDetailInfoMapper.toEntity(new ArrayList(productDetailInfoDTOS));
            for(ProductDetailInfo details:productDetailInfos){
                details.setCreationTime(ZonedDateTime.now());
                details.setCreatorUserId(SecurityUtils.getCurrentUserId());
                details.setLastModificationTime(ZonedDateTime.now());
                details.setLastModifierUserId(SecurityUtils.getCurrentUserId());
            }
            productDetailInfos = productDetailInfoRepository.save(productDetailInfos);
            productInfoDTO.setProductDetailInfoDTOS(new HashSet<>(productDetailInfoMapper.toDto(productDetailInfos)));
        }
        return BaseDTO.createBaseDTO(productInfoDTO);
    }

    /**
     * 删除货物信息
     * @param id
     * @return
     */
    public BaseDTO deleteProductInfoById(String id){
        if(id==null || "".equals(id)){
            return new BaseDTO(BaseDTO.CODE_PARAM, "product_info_key_not_null", null);
        }
        ProductInfo productInfo = productInfoRepository.findOne(id);
        productInfo.setDeletedFlag(true);
        productInfo.setDeletionTime(ZonedDateTime.now());
        productInfo.setDeleterUserId(SecurityUtils.getCurrentUserId());
        //删除货物信息
        productInfoRepository.save(productInfo);

        List<ProductDetailInfo> productDetailInfos = productDetailInfoRepository.findAllByInfoIdAndDeletionTimeIsNull(id);
        if(productDetailInfos!=null && !productDetailInfos.isEmpty()){
            for(ProductDetailInfo detailInfo:productDetailInfos){
                detailInfo.setDeletedFlag(true);
                detailInfo.setDeletionTime(ZonedDateTime.now());
                detailInfo.setDeleterUserId(SecurityUtils.getCurrentUserId());
            }
        }
        //删除商品明细
        productDetailInfoRepository.save(productDetailInfos);



        return BaseDTO.createBaseDTO();
    }


}
